import React, { Component, Fragment } from "react"
import TodoItem from "./TodoItem"
import AnimateTest from "./AnimateTest"
import CSSTransitionTest from "./CSSTransitionTest"
import TransitionGroupTest from "./TransitionGroupTest"

class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: "",
      list: [],
      text: "my name is test!",
      content: "点击更改内容"
    }
  }

  // componentDidMount() {
  //   axios.get('/api/todolist').then((res)=>{
  //     this.setState(()=>({
  //       list: [...res.data]
  //     }))
  //   })
  // }

  handleInputChange = e => {
    const value = e.target.value
    this.setState(state => {
      return {
        inputValue: value
      }
    })
    // this.setState({
    //   inputValue: e.target.value
    // })
  }

  // 第一种方式：
  // handleBtnClick = e => {
  //   this.setState(state => {
  //     state.list.push('123')
  //     return {
  //       list: state.list // 比较错误的方式
  //     }
  //   })
  // }

  // 第二种方式
  handleBtnClick = e => {
    this.setState(
      state => ({
        inputValue: "",
        list: [...state.list, state.inputValue]
      }),
      () => {
        console.log(this.ul.querySelectorAll("li").length)
      }
    )
  }

  // 第一种方式：
  // handleItemDelete = (i) => {
  //   this.setState(state => ({
  //     list: state.list.filter((item,index) => i !== index)
  //   })
  //   )
  // }

  // 第二种方式：
  handleItemDelete = i => {
    let list = [...this.state.list]
    list.splice(i, 1)
    this.setState({
      list
    })
  }

  handleChangeContent = () => {
    this.setState({
      content: "更改之后"
    })
  }

  getTodoItem() {
    return this.state.list.map((item, i) => (
      <TodoItem
        key={i}
        text={this.state.text}
        content={item}
        handleClick={e => {
          console.log(e.target)
          this.handleItemDelete(i)
        }}
      />
    ))
  }

  render() {
    return (
      <Fragment>
        <h1 onClick={this.handleChangeContent}>{this.state.content}</h1>
        <label htmlFor="todoInput">请输入内容：</label>
        <input
          className="myNameIsInput"
          id="todoInput"
          value={this.state.inputValue}
          onChange={this.handleInputChange}
          type="text"
          ref={input => {
            this.input = input
          }}
        />
        <button onClick={this.handleBtnClick}>提交</button>
        <ul
          ref={ul => {
            this.ul = ul
          }}
        >
          {this.getTodoItem()}
        </ul>
        <AnimateTest content={this.state.testContent} />
        <br />
        <br />
        <CSSTransitionTest />
        <br />
        <br />
        <TransitionGroupTest />
      </Fragment>
    )
  }
}

export const o = "zhaoenxiao"

export default TodoList
